<?php
/**
 * Created by PhpStorm.
 * User: trisatria
 * Date: 1/6/14
 * Time: 1:17 PM
 */
namespace Admin\Controller;
use Admin\Form\AdminUserForm;
use Admin\Model\AdminUser;
use Admin\Model\AdminUserMessage;
use Application\Controller\GlobalController;
use Velacolib\Utility\Utility;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Velacolib\Utility\ultility;
use Zend\View\Model\JsonModel;

class UserController extends AbstractActionController
{
    protected  $userTable;
    protected $sm;
    protected $service_locator_str;
    protected $auth;

    protected $friendTable;
    protected $userMessage;

    protected $topicModel;

    public function onDispatch(\Zend\Mvc\MvcEvent $e){

        $this->service_locator_str = 'Admin\Model\AdminUserTable';
        $this->sm = $this->getServiceLocator();
        $this->userTable = $this->sm->get($this->service_locator_str);

        $str = 'Admin\Model\AdminFriendsTable';
        $this->sm = $this->getServiceLocator();
        $this->friendTable = $this->sm->get($str);

        $str = 'Admin\Model\AdminUserMessageTable';
        $this->sm = $this->getServiceLocator();
        $this->userMessage = $this->sm->get($str);

        $str = 'Admin\Model\AdminUserMessageTable';
        $this->sm = $this->getServiceLocator();
        $this->userMessage = $this->sm->get($str);

        $str = 'Admin\Model\AdminTopicTable';
        $this->sm = $this->getServiceLocator();
        $this->topicModel = $this->sm->get($str);

        $this->auth = Utility::CheckLogin($this);
        if ($this->auth!=null && $this->auth->user_type != 3 ) {
            $this->redirect()->toRoute('admin/child',array('controller'=>'login'));
        }
        if ($this->auth==null){
            $this->redirect()->toRoute('admin/child',array('controller'=>'login'));
        }
        return parent::onDispatch($e);
    }

    public function init(){
        //$this->Acl->SetModule('Project');
        //if(!$this->Acl->Check())
          //  $this->redirect()->toRoute('home', array ('action' => 'index'));
    }

    public function indexAction()
    {
        if (!$this->userTable) {
            $sm = $this->getServiceLocator();
            $this->userTable = $sm->get('Admin\Model\AdminUserTable');
        }
        $paginator = $this->userTable->fetchAll();
        $paginator->setCurrentPageNumber((int)$this->params()->fromQuery('page', 1));
        $search_val = $this->params()->fromQuery('search_val');
        $array_return =  array('users' => $paginator);
        if(isset($search_val)){

            $paginator = $this->userTable->searchFullText($search_val);
            $array_return['search_val'] = $search_val;
            $array_return['users'] = $paginator;
        }

        // set the number of items per page to 10
        $paginator->setItemCountPerPage(ITEM_PER_PAGE);
        return new ViewModel( $array_return);
    }

    public function addAction(){
        $user_static_array = array();
        $form = new AdminUserForm();
        $form->get('submit')->setValue('Add');
        $request = $this->getRequest();
        if($request->isPost()){
            $user = new AdminUser();
            $form->setInputFilter($user->getInputFilter());
            $form->setData($request->getPost());
            if($form->isValid()){
                $data = $form->getData();
                $data['time_reg'] = time();
                $data['confirm'] = 0;
                $user_model = new AdminUser();
                $user_model->exchangeArray($data);
                $this->userTable->saveUser($user_model);
            }
        }




        return array('form' => $form);
    }


    public function deleteAction(){
        $id = $this->params()->fromRoute('id',0);
        if(!$id){
        }
        else{
            $this->userTable->deleteUser($id);
        }
    }


    public function editAction(){
        $id = $this->params()->fromRoute('id');
        if(!$id){
            return $this->redirect()->toRoute('admin/child',array('controller'=>'user','action'=>'add'));
        }
        else{
           $user_info = $this->userTable->getUser($id);
            $user_static_array = array();
            $form = new AdminUserForm();
            $form->get('submit')->setValue('Edit');
            $form->get('id')->setValue($user_info->id);
            $form->get('name')->setValue($user_info->name);
            $form->get('email')->setValue($user_info->email);
            $form->get('address')->setValue($user_info->address);
            $form->get('phone')->setValue($user_info->phone);
            $form->get('avatar')->setValue($user_info->avatar);
            $form->get('password')->setValue($user_info->password);
            $form->get('status')->setValue($user_info->status);

            $form->get('user_type')->setValue($user_info->user_type);
            $request = $this->getRequest();
            if($request->isPost()){
                $user = new AdminUser();
                $form->setInputFilter($user->getInputFilter());
                $form->setData($request->getPost());
                if($form->isValid()){
                    $data = $form->getData();
                    $data['password'] = md5($data['email'].$data['password']);
                    $user_model = new AdminUser();
                    $user_model->exchangeArray($data);
                    $this->userTable->saveUser($user_model);
                }
            }
           return new ViewModel(array('user_info'=>$user_info, 'form' => $form));
        }

    }

    public function detailAction(){
        
        $user_id = $this->params()->fromRoute('id');

        //get user info
        $user_info = $this->userTable->getUser($user_id);
        //get all friends + flow of user
        $friend_paginator =  $this->friendTable->fetchAll($user_id);
        $friend_paginator->setCurrentPageNumber((int)$this->params()->fromQuery('page', 1));
        $friend_paginator->setItemCountPerPage(ITEM_PER_PAGE);
        //check friend with user
        $is_friend = $this->friendTable->checkFriend($this->auth->userid,$user_id);

        //new message
        $message_new = $this->userMessage->fetchNew($this->auth->userid);

        $where['user_id'] = $user_id;

        $topic_of_user = $this->topicModel->fetchTopicWhere($where);
        $topic_of_user->setCurrentPageNumber((int)$this->params()->fromQuery('page', 1));
        $topic_of_user->setItemCountPerPage(ITEM_PER_PAGE);

        return array('info' => $user_info, 'friends' => $friend_paginator, 'user_id'=>$user_id, 'auth'=>$this->auth,'is_friend'=>$is_friend , 'message_new'=>$message_new,'topicUser'=>$topic_of_user);

    }

    public function AddFriendAction(){
        $data = $this->params()->fromPost();
        $userMessage = new AdminUserMessage();
        $userMessage->exchangeArray($data);
        $is_follow = $data['type_request'];

        if($is_follow == 0){
            echo $this->userMessage->saveAddMessage($userMessage);
        }
        else{
            $data1 = array(
                'user_id' => $this->auth->userid,
                'friend_id' => $data['to_user'],
                'follow' => '1',
            );
            $this->friendTable->addFriend($data1);
            echo 1;
        }
        die;
    }

    public function AcceptFriendAction(){
        $data = $this->params()->fromPost();
        //add new friend;
        $user_id = $data['user_id'];
        $friend_id = $data['friend_id'];
        $message_id = $data['message_id'];
        unset($data['message_id']);

        //check friend
        $is_friend = $this->friendTable->checkFriend($user_id, $friend_id);
        if(!$is_friend)
        {
            //if not a friend
            if($data['follow'] == 1){
                $this->friendTable->addFriend($data);
            }
            if($data['follow'] == 0){
                $this->friendTable->addFriend($data);
                $data['user_id'] = $friend_id;
                $data['friend_id'] = $user_id;
                $this->friendTable->addFriend($data);
            }

            //update user's message
            $message = $this->userMessage->getMessage($message_id);
            $message->is_accepted = 1;
            $message = $this->userMessage->saveAddMessage($message);
            $this->userMessage->deleteUserMessage($message_id);
        }
        echo  $is_friend;
        die;
    }

    public function LoadEmailAction(){
        //delete email
        $request = $this->getRequest();
        if($request->isPost()){
            $this->userMessage->deleteUserMessage($this->params()->fromPost('message_id'));
            echo 1;
            die;
        }

        //load email
        $id = $this->params()->fromRoute('id');
        if(!$id)
            $this->redirect()->toRoute('admin/child',array('controller'=>'topic'));
        //all message of user
        $message_all = $this->userMessage->fetchAll($this->auth->userid);
        $message_all->setCurrentPageNumber((int)$this->params()->fromQuery('page', 1));
        // set the number of items per page to 10
        $message_all->setItemCountPerPage(ITEM_PER_PAGE);
        return array('message' => $message_all, 'auth'=>$this->auth);
    }

    public function LoadNewEmailAjaxAction(){

        $message_new = $this->userMessage->fetchNew($this->auth->userid);
        echo $message_new->getCurrentItemCount();
        die;
    }

    public function FriendTopicAction(){
       // $this->geta
        $friend_topic = $this->friendTable->getFriendTopic($this->auth->userid,0,100);
        $newest = $friend_topic[0]['topic_id'];
        $get_data = $this->params()->fromQuery();
        //check new
        if(isset($get_data['check'])){
            if($get_data['check'] == 1)
            {
                if(isset($get_data['newest'])){
                    if($get_data['newest'] != $newest){
                        echo 1;
                    }
                    else{
                        echo 0;
                    }
                }

            }
        }
        //fetch
        else{
            // Find out how many items are in the table
            $total = count($friend_topic);
            // How many items to list per page
            $limit = 10;
            // How many pages will there be
            $pages = ceil($total / $limit);
            //current page
            $page = $this->params()->fromQuery('page');
            // Calculate the offset for the query
            $offset = ($page - 1)  * $limit;
            // Some information to display to the user
            $start = $offset;
            $end = min(($offset + $limit), $total);

            if($page < $pages){
                $friend_topic = $this->friendTable->getFriendTopic($this->auth->userid,$start,$end);
                echo json_encode($friend_topic);
            }

        }
        die;
    }
    public function WallAction(){

    }
}